import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:eplorex/pages/my/profile/edit_user_birthday_page.dart';
import 'package:eplorex/pages/my/profile/edit_user_gender_page.dart';
import 'package:eplorex/pages/my/profile/edit_user_name_page.dart';
import 'package:eplorex/pages/my/profile/edit_user_school_page.dart';
import 'package:flutter/material.dart';

import '../../dao/user_profile_dao.dart';
import '../../models/base_contanst.dart';
import '../../models/user/UserBaseInfo.dart';
import '../../utils/HttpUtil.dart';
import '../../utils/ImagePickerUtils.dart';

class MyEditProfilePage extends StatefulWidget {
  const MyEditProfilePage({super.key});

  @override
  State<MyEditProfilePage> createState() => _MyEditProfilePageState();
}

class _MyEditProfilePageState extends State<MyEditProfilePage> {
  TextStyle? _textStyleDefault = TextStyle(fontSize: 20);
  CityPickerUtil cityPickerUtils = CityPickers.utils();

  Future<UserBaseInfo>? _userProfile;

  UserBaseInfo? _useBaseInfo;

  String? _cityName;

  @override
  void initState() {
    _userProfile = UserProfileDao.queryCurUserProfile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("编辑资料"),
      ),
      body: FutureBuilder(
          future: _userProfile,
          builder: (BuildContext context, AsyncSnapshot<UserBaseInfo> snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting ||
                !snapshot.hasData) {
              return const Center(
                child: Text("loading....."),
              );
            }

            _useBaseInfo = _useBaseInfo ??  snapshot.data!;
            if(_cityName==null){
              Result result= cityPickerUtils.getAreaResultByCode(_useBaseInfo?.city ?? '110000');
              _cityName=result.cityName;
            }
            return ListView(
              children: [
                Container(
                  // margin: EdgeInsets.symmetric(horizontal: 40,vertical: 10),
                  // color: Colors.red,
                  height: 200,
                  child: Center(
                      child: Stack(
                    children: [
                      CircleAvatar(
                        radius: 60,
                        backgroundImage: NetworkImage(
                            _useBaseInfo!.avatar ?? ""),
                      ),
                      Positioned(
                          right: -10,
                          bottom: -10,
                          child: Container(
                              child: IconButton(
                                  padding: EdgeInsets.zero,
                                  style: ButtonStyle(
                                      minimumSize: MaterialStateProperty.all(
                                          Size.fromRadius(16)),
                                      backgroundColor:
                                          MaterialStateProperty.all(
                                              Colors.white)),
                                  onPressed: () {
                                    showModalBottomSheet(
                                        constraints:
                                            BoxConstraints(maxHeight: 220),
                                        context: context,
                                        builder: (context) {
                                          return Center(
                                            child: Padding(padding: EdgeInsets.symmetric(vertical: 20),
                                              child: Column(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              children: [
                                                ListTile(
                                                    title: Text(
                                                      "从微信导入",
                                                      style: _textStyleDefault,
                                                    )),
                                                ListTile(
                                                    title: Text("从微信导入",
                                                        style:
                                                        _textStyleDefault)),
                                                ListTile(

                                                    title: Text("从手机相册选择",
                                                        style:
                                                        _textStyleDefault),
                                                  onTap: (){
                                                    _editAvatar(context);
                                                    Navigator.pop(context);
                                                  },
                                                )
                                              ],
                                            ),),
                                          );
                                        });
                                  },
                                  icon: Icon(
                                    Icons.camera_alt_outlined,
                                    color: Colors.black,
                                  ))))
                    ],
                  )),
                ),
                ListTile(
                  title: Text(
                    '名字',
                    style: _textStyleDefault,
                  ),
                  trailing: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(
                        _useBaseInfo!.userName!,
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (_) =>
                            EditUserName(_useBaseInfo!.userName ?? "")));
                  },
                ),
                ListTile(
                  title: Text(
                    '性别',
                    style: _textStyleDefault,
                  ),
                  trailing: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(
                        Gender.findById(_useBaseInfo?.gender ?? 0).desc,
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (_) => EditUserGenderPage(gender: _useBaseInfo?.gender,valueChanged: (value) {
                          setState(() {
                            _useBaseInfo?.gender=value;
                          });
                        },)));
                  },
                ),
                ListTile(
                  title: Text(
                    '生日',
                    style: _textStyleDefault,
                  ),
                  trailing: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text( _useBaseInfo!.birthDay ?? '2024-09-01',
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (_) => EditBirthDayPage(
                              birthDay: _useBaseInfo!.birthDay ?? '2024-09-01',
                              changed: (value) {
                                setState(() {
                                  _useBaseInfo!.birthDay  = value;
                                });
                              },
                            )));
                  },
                ),
                ListTile(
                  title: Text(
                    '地区',
                    style: _textStyleDefault,
                  ),
                  trailing:  Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(
                        _cityName  ?? '上海',
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                  onTap: () {
                    _showCity();
                  },
                ),
                ListTile(
                  title: Text(
                    '学校',
                    style: _textStyleDefault,
                  ),
                  trailing: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(
                        _useBaseInfo!.school ?? " ",
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                  onTap: () {
                    Navigator.of(context).push(MaterialPageRoute(
                        builder: (_) => EditUserSchoolPage(valueChanged: (value) {
                           setState(() {
                             _useBaseInfo!.school=value;
                           });
                        },)));
                  },
                ),
                ListTile(
                  title: Text(
                    '背景图',
                    style: _textStyleDefault,
                  ),
                  trailing: const Wrap(
                    crossAxisAlignment: WrapCrossAlignment.center,
                    children: [
                      Text(
                        "",
                        style: TextStyle(fontSize: 16),
                      ),
                      Image(
                        image: AssetImage("images/arrow_right_icon.png"),
                        width: 20,
                      )
                    ],
                  ),
                  splashColor: Colors.black,
                ),
              ],
            );
          }),
    );
  }

  _showCity() async {
    Result? result = await CityPickers.showCitiesSelector(
      context: context,
      useSearchAppBar: true,
    );
    setState(() {
      _cityName= result?.cityName ?? '上海';
    });

    HttpUtil.getInstance().post('/api/user/v1/my/profile/edit/city', data: result?.cityId);
  }

  _editAvatar(BuildContext context) async {
    List<FileWrapper> files= await selectImage(context);
    List<String>? avatars= await compressAndUploadPics(files);
    if(avatars!=null && avatars.length>0){
      setState(() {
        _useBaseInfo!.avatar= avatars?.first;
      });
      HttpUtil.getInstance().post('/api/user/v1/my/profile/edit/avatar', data: avatars?.first);
    }
  }
}
